<template>
  <section>
    <el-table class="tab-table" :data="value" :span-method="spanMethod" border>

      <el-table-column prop="title" :label="$t('message.setting.msgTab.c1')" min-width="180" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{row.title}}
          <template v-if="row.desc">
            <!-- 工单池订阅内容太多需要换行前端单独处理 -->
            <template v-if="row.messageTypeName === 'SubTaskPool_NEW'">
              <el-tooltip placement="top">
                <div slot="content">
                  <p></p>
                  <p>{{ $t('message.setting.msgTab.t1') }}</p>
                  <p>{{ $t('message.setting.msgTab.t2') }}</p>
                  <p>{{ $t('message.setting.msgTab.t3') }}</p>
                </div>
                <i class="iconfont icon-fdn-info"></i>
              </el-tooltip>
            </template>

            <template v-else>
              <el-tooltip :content="row.desc" placement="top">
                <i class="iconfont icon-fdn-info"></i>
              </el-tooltip>
            </template> 
            
          </template>
        </template>

      </el-table-column>

      <template v-if="module == 'project'">
        <el-table-column  prop="triggerTarget" :label="$t('projectManage.setting.messageSetting.label1')" min-width="180" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span v-if="row.triggerTarget === 'PROJECT'">{{$t('projectManage.setting.messageSetting.option1')}}</span>
            <span v-if="row.triggerTarget === 'TASK' && row.triggerType === 'SINGLE'">{{$t('projectManage.setting.messageSetting.option2')}}/{{row.projectTaskConfigName }}</span>
            <span v-if="row.triggerTarget === 'TASK' && row.triggerType === 'ALL'">{{$t('projectManage.setting.messageSetting.allOption')}}</span>
          </template>
        </el-table-column>
        <!-- 触发的类型 -->
        <el-table-column prop="triggerTimeType" :label="$t('projectManage.setting.messageSetting.label4')" min-width="180" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span v-if="row.triggerTimeType === 'FIXED_TIME'">{{$t('projectManage.setting.messageSetting.option4')}}</span>
            <span v-if="row.triggerTimeType === 'REAL_TIME'">{{$t('projectManage.setting.messageSetting.option5')}}</span>
          </template>
        </el-table-column>
        <el-table-column  prop="triggerDateRule" :label="$t('projectManage.setting.messageSetting.label2')" min-width="180" show-overflow-tooltip>
          <template slot-scope="{row}">
            <!-- 定时触发 -->
            <span v-if="row.triggerDateRule && row.triggerDateRule.timeName && row.triggerTimeType === 'FIXED_TIME'">{{row.triggerDateRule.timeTypeAllName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="triggerAction" :label="$t('projectManage.setting.messageSetting.label5')" min-width="180" show-overflow-tooltip>
          <template slot-scope="{row}">
            <!-- 实时触发 -->
            <span v-if="row.triggerAction && row.triggerTimeType === 'REAL_TIME'">{{$t('projectManage.setting.messageSetting.option6')}}</span>
          </template>
        </el-table-column>
      </template>
      <template v-else>
        <el-table-column prop="nodeDesc" :label="$t('message.setting.msgTab.c2')" min-width="180" show-overflow-tooltip></el-table-column>
      </template>
      <el-table-column  min-width="200">
        <template slot="header" slot-scope="{row, $index}">
          {{ $t('message.setting.msgTab.t4') }}<span style="color:#8c8c8c;font-size: 12px;">{{ $t('message.setting.msgTab.t5') }}</span>
        </template>  

        <template slot-scope="{row,$index}">
          <el-button 
            type="text" 
            v-if="row.messageTypeName === 'TaskPlanRemind_NEW' || row.messageTypeName === 'TaskOverTime_NEW'" 
            @click="gotoSetPage">
            {{ $t('message.setting.msgTab.t6') }}
          </el-button>

          <el-button 
            type="text" 
            v-else-if="row.messageTypeName === 'EventOverTime_NEW'" 
            @click="gotoEventSettingPage">
            {{ $t('message.setting.msgTab.t7') }}
          </el-button>

          <template v-else-if="!(['satisfactionReturnVisitV2', 'callCenterCallInNotDealHangupRemind', 'satisfactionCallcenter'].includes(row.messageTypeName))">
            <el-button type="text" @click="openSetMessageDialog('inside',row)">
              {{ $t('message.setting.msgTab.t8') }}
            </el-button>

            <template v-if="module !== 'universal'">
              <el-switch 
                v-model="row.insideSwitch"
                :key="row.bizId"
                @change="(val) => {switchChangeHandle($index,'inside', row)}">
              </el-switch>

              <span class="statue">{{row.insideSwitch?$t('common.base.open'):$t('common.base.close')}}</span>
            </template>
          </template>
          
        </template>
      </el-table-column>

      <el-table-column v-if="showExternalColumn && activeModule !== 'course'" min-width="200">
        <template slot="header" slot-scope="{row, $index}">
          {{ $t('message.setting.msgTab.t9') }}<span style="color:#8c8c8c;font-size: 12px;">{{ $t('message.setting.msgTab.t10') }}</span>
        </template>
        <template slot-scope="{row,$index}">
          <!-- 会话超时提醒不需要展示 -->
          <template v-if="row.messageTypeName !== 'ConversationTimeOut'">
            <el-button type="text" @click="openSetMessageDialog('customer',row)" >
              {{ $t('message.setting.msgTab.t8') }}
            </el-button>
            <el-switch
              v-model="row.customerSwitch"
              :key="row.bizId"
              @change="(val) => {switchChangeHandle($index,'customer', row)}">
            </el-switch>

            <span class="statue">{{row.customerSwitch?$t('common.base.open'):$t('common.base.close')}}</span>
          </template>
        </template>
      </el-table-column>

      <!-- 操作栏 目前仅供paas使用 -->
      <el-table-column v-if="showOperateColumn" :label="$t('common.base.operation')" min-width="110">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleEditColumn(row)" :disabled="row.isSystem === 1">
            {{ $t('common.base.edit') }}
          </el-button>
          <el-button type="text" @click="handleDeleteColumn(row)" :disabled="row.isSystem === 1">
            {{  $t('common.base.delete') }}
          </el-button>
        </template>
      </el-table-column>
      <template slot="empty">
        <no-data-view-new :notice-msg="$t('common.base.tip.noData')" />
     </template>
    </el-table>

    <!-- 设置消息弹框 -->
    <SetMessageDialog 
      v-if="messageDialogVisible"
      v-model="messageDialogVisible"
      :type="messageDialogType"
      :message-type-name="messageTypeName"
      :message-trigger-type="messageTriggerType"
      :messageTriggerTypeItem="messageTriggerTypeItem"
      :project-task-obj="projectTaskObj"
      :projectTypeId="projectTypeId"
      :config-id="configId"
      :report-send-time="reportSendTime"
      :active-module="activeModule"
      @getListByModule="$emit('getListByModule')"
    />
  </section>
</template>

<script>
// 设置消息模版
import SetMessageDialog from '../dialog/SetMessageDialog.vue'

import NoDataViewNew from '@src/component/common/NoDataViewNew';
// 接口
import * as Message from '@src/api/Message';

import { switchMessageRule, taskItemDetail } from '@src/api/ProjectManage.ts'

import { openAccurateTab } from '@src/util/platform';

import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum'

import { t } from '@src/locales'
export default {
  name:'message-table',

  data(){
    return {
      messageDialogVisible:false,
      // 消息类型 inside：内部，customer：客户
      messageDialogType:'',
      // 消息类型名称英文
      messageTypeName:'',
      // 消息的id，取自内部消息和客户消息的id
      configId:'',

      // 项目管理触发对象的类型 任务/项目
      messageTriggerType:'',

      // 项目管理触发对象的具体任务类型 单个任务/全部任务
      messageTriggerTypeItem: '',

      // 任务表单id/任务类型
      projectTaskObj: {
        taskFormId: '',
        taskType: '',
      },
    }
  },

  props:{
    // 是否展示客户消息这一列
    showExternalColumn:{
      type:Boolean,
      required:true
    },
    value:{
      type:Array,
      required:true
    },

    projectTypeId: {
      type:String,
      required:false
    },

    reportSendTime:{
      type:String,
      required:false
    },
    // 是否显示操作栏
    showOperateColumn: {
      type: Boolean,
      default: ()=> false
    },
    switchFetchFun: {
      type: Function,
      default: Message.msgConfigSwitch
    },
    spanMethod: {
      type: Function,
      default: ()=> {}
    },
    activeModule:{
      type:String,
      default:''
    }
  },

  inject: ['module'],

  components:{
    SetMessageDialog,
    NoDataViewNew
  },

  methods:{
    handleEditColumn(row) {
      this.$emit('handleEditColumn', row)
    },
  
    handleDeleteColumn(row) {
      this.$emit('handleDeleteColumn', row)
    },

    gotoSetPage(){
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskTypeManage,
        reload: true,
        titleKey: '工单类型设置',
        fromId
      })
    },

    gotoEventSettingPage(){
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceStation,
        titleKey: '事件类型设置'
      })
    },

    getSwitchParam(index, type){
      const { insideSwitch, customerSwitch, insideConfigId, customerConfigId } = this.value[index]

      if( type === 'inside'){
        return {
          isSwitch:insideSwitch,
          id:insideConfigId,
          switchKey:'insideSwitch'
        }
      }
      
      return {
        isSwitch:customerSwitch,
        id:customerConfigId,
        switchKey:'customerSwitch'
      }
    },

    // 改变模板开启禁用
    async switchChangeHandle(index, type, row) {

      const { messageTypeName, ruleType = '' } = row
      
      const { isSwitch, id, switchKey } = this.getSwitchParam(index, type)
       

      let param = {
        isSwitch,
        id,
      }


      let value = [...this.value]

      try {
        // 如果是paas处理
        if(this.module === 'paas') {
          param.type = type
          param.bizId = row?.bizId || ''
          param.ruleType = ruleType
        } else if (this.module === 'project') {
          let projectParams = {
            type: type === 'inside' ? 'INSIDE' : 'OUTSIDE',
            id: row.id,
            projectTypeId: this.projectTypeId,
            enable: isSwitch,
          }
          switchMessageRule(projectParams).then((res) => {
            console.log(res, 'res')
            if (res.status === 0) {
              this.$emit('getListByModule')
            }
          })
          return
        } else {
          // 开启时校验
          isSwitch && (this.checkTips(id, messageTypeName));
        }

        const { status, message } = await this.switchFetchFun(param);

        // 接口调用成功
        if(status === 0){
          this.$emit('getListByModule')
          return
        }

        this.$platform.notification({
          type: 'error',
          title: t('common.base.fail'),
          message
        });

        // 更新失败，需要将switch的值设置回去
        value[index][switchKey] = !isSwitch
        this.$emit('input', value)

      } catch (error) {
        console.log(error);
      }
    },

    // 开启配置，需要校验一些配置
    async checkTips(configId, messageTypeName){
      let errTextArr = [];

      // 查询消息设置的渠道是否全部关闭
      const checkChannelRes = await Message.checkChannelAllClose({configId});

      checkChannelRes?.data && errTextArr.push(t('message.setting.msgTab.t11'));

      // 工单计划时间提醒通知 判断有没有设置事件，没有设置时间自动关闭
      // 没有时间时，提示客户：“请点击消息设置，设置消息发送的时间”
      if(messageTypeName && messageTypeName === 'TaskPlanRemind_NEW'){
        const checkHasTaskTimeRes = await Message.checkHasTaskPlanTime()
        checkHasTaskTimeRes?.data && errTextArr.push(t('message.setting.msgTab.t12'));
      }
      
      errTextArr.length && this.$message({
        customClass:'valid-error-tips',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        message: `${errTextArr.join('<br/>')}`
      });
    },

    async openSetMessageDialog(messageDialogType, row){
      const { messageTypeName, insideConfigId, customerConfigId, triggerTarget, triggerType} = row

      this.configId = messageDialogType === 'customer' ? customerConfigId : insideConfigId

      this.messageDialogType = messageDialogType

      this.messageTypeName = messageTypeName

      this.messageTriggerType = triggerTarget


      if (this.module === 'project') {
        if (this.messageTriggerType === 'TASK') {
          if (row.projectTaskConfigId) {
            let params = {
              id: row.projectTaskConfigId,
              projectTypeId: this.projectTypeId,
            }
            await taskItemDetail(params).then((res) => {
              if (res.success) {
                const { taskFormId, taskType } = res.data
                this.projectTaskObj.taskFormId = taskFormId
                this.projectTaskObj.taskType = taskType
              }
            })
          }
          // 区分是全部任务/还是单个任务
          this.messageTriggerTypeItem = triggerType
        }

        // 项目类型 直接打开弹窗
        this.messageDialogVisible = true
      } else {
        // 打开设置弹框
        this.messageDialogVisible = true
      }

    },
  }
}
</script>


<style lang="scss" scoped>

.el-table--border {
    border-top:1px solid #ebeef5;
    border-left:1px solid #ebeef5;
    &::after {
        width: 1px !important;
    }
    .el-table__empty-block{
      border-bottom:1px solid #ebeef5;
    }
}
.tab-table ::v-deep{
    .el-switch{
        margin:0 12px 0 24px;
    }
    .statue{
        color:#595959;
    }
    .cell{
        color:#262626;
    }
    thead th{
        background:#FAFAFA;
        font-weight: 300;
        padding: 3px 0!important;
    }
    i {
      color: #8c8c8c;
      margin-left: 5px;
    }
}
::v-deep .el-table__empty-block{
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 40px;
}

::v-deep .tab-table tbody tr:hover>td { 
     background: transparent !important;
  }

</style>
